import Interact from '../utils/interact'
import baseUrl from './baseUrl'
// @ts-ignore 忽略类型检查，因为store模块没有类型声明文件
import Store from '../store'
import { globalLogin } from '@/hooks/login'
import { nextTick } from 'vue'

let showingToast = false
function ShowToast(msg: string) {
    showingToast = true
    Interact.toast(msg)
    setTimeout(() => {
        showingToast = false
    }, 3000)
}

export default {
    request: (_options: Partial<Http.RequestOptions>) => {
        return new Promise<Http.ResponseRes>((resolve, reject) => {
            const options: Http.RequestOptions = Object.assign(
                {
                    method: "POST", // 请求方式
                    url: "", // 请求地址
                    data: {}, // 请求数据
                    params: {}, // 请求参数
                    header: {
                        // 'Content-Type': 'multipart/form-data'
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                    resolveAllData: false,
                    filterErrCode: void 0, //过滤掉一部分错误code不走默认的错误处理(String, Array, Number 都可以)
                    noErrorToast: false,
                    complete: null, // 请求结束后的回调函数（无论是否成功都会被调用）
                    loadingIcon: true, // 是否显示loading状态动画
                    relayLoading: false, //接力加载，只开始loading图标，但是不关闭
                    timeout: 20000, // 超时时间。默认30000ms
                },
                _options
            );

            if (options.url.indexOf("http") == -1) {
                options.url = baseUrl + options.url;
            }
            // 1秒钟内能返回的接口不弹出loading
            let loadingTimer: number;
            if (options.loadingIcon) {
                loadingTimer = setTimeout(() => {
                    if (showingToast) return;
                    uni.showLoading({
                        title: "加载中",
                        icon: "loading",
                        mask: true,
                    });
                }, 200);
            }
            options.data = options.data || {};
            options.data = {
                merNo: Store.state.shop.merNo,
                platCode: Store.state.shop.platCode,
                ...options.data,
            }
            if (Store.state.user.account.token) {
                options.data = {
                    token: Store.state.user.account.token,
                    ...options.data,
                };
            }
            // let dataStr
            // for(let key in options.data) {
            //     if(!options.data[key]) {
            //         delete options.data[key]
            //     }
            //     dataStr += `${key}=${options.data[key]}&`
            // }
            // options.data = dataStr.slice(0, -1)

            let requestCon: UniApp.RequestOptions = {
                url: options.url,
                method: options.method || "POST",
                data: options.data,
                timeout: options.timeout || 10000,
                complete: () => {
                    if (options.loadingIcon && !options.relayLoading) {
                        clearTimeout(loadingTimer);
                        uni.hideLoading();
                    }
                    nextTick(() => {
                        typeof options.complete === "function" &&
                            options.complete();
                    });
                },
                success: (res: UniNamespace.RequestSuccessCallbackResult) => {
                    if (res.statusCode === 200) {
                        const data = res.data as Http.ResponseRes;
                        if (options.resolveAllData) {
                            return resolve(data);
                        }
                        if (data.code === 1) {
                            resolve(data);
                        } else if (data.code == 10001) {
                            Store.commit("user/CLEAR_USER_ACCOUNT");
                            Interact.modal({
                                title: "登录提示",
                                message: "登录失效，请重新登录",
                                showCancel: true,
                            }).then((action) => {
                                if (action.confirm) {
                                    globalLogin()
                                }
                            });
                        } else {
                            if (options.filterErrCode) {
                                // 特定的code不弹出错误提示
                                if (
                                    typeof options.filterErrCode == "number" &&
                                    data.code == options.filterErrCode
                                ) {
                                } else if (
                                    options.filterErrCode instanceof Array &&
                                    options.filterErrCode.indexOf(data.code) >
                                        -1
                                ) {
                                } else {
                                    ShowToast(data.msg);
                                }
                            } else {
                                if (!options.noErrorToast) {
                                    ShowToast(data.msg);
                                }
                            }
                            reject(res.data);
                        }
                    } else {
                        let statusCode: number = res.statusCode;
                        ShowToast(
                            {
                                400: "请求错误",
                                401: "未授权，请登录",
                                403: "拒绝访问",
                                404: "请求地址错误：" + options.url,
                                408: "请求超时",
                                500: "服务器内部错误",
                                501: "服务未实现",
                                502: "网关错误",
                                503: "服务不可用",
                                504: "网关超时",
                                505: "HTTP版本不受支持",
                            }[statusCode] || "错误" + res.statusCode
                        );
                    }
                },
                fail: (err: any) => {
                    console.error(err, options.url);
                    ShowToast("网络错误，请重试");
                    reject(err);
                },
            };
            if (options.header) {
                requestCon.header = options.header;
            }
            uni.request(requestCon);
        });
    },
};
